package com.example.springboot.model;

import com.google.gson.Gson;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

@Slf4j
public class ApiService {

    private static final String hostUrl = "https://spark-api.xf-yun.com/v1.1/chat";
    private static final String appid = "c69853eb";
    private static final String apiSecret = "YzRjODA0MTNhMDA1NTU0YTMyNTI4NzQw";
    private static final String apiKey = "427635d6793f3be5c1ad8e66d75cb5ac";
    private static final Gson gson = new Gson();

//     设置 OkHttpClient 日志级别为 FINE
//    static {
//        Logger.getLogger(OkHttpClient.class.getName()).setLevel(Level.FINE);
//    }

    public void sendRequest(String text, Session session) throws Exception {
        String authUrl = Utils.getAuthUrl(hostUrl, apiKey, apiSecret);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(authUrl).build();
        WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
                super.onOpen(webSocket, response);
                try {
                    sendChatRequest(webSocket, text, session);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
                log.info("processResponse: {}", text);
                log.info("session: {}", session.getRequestURI().getQuery());
                processResponse(text, session);
            }

            @Override
            public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, Response response) {
                super.onFailure(webSocket, t, response);
            }
        });
    }

    private void sendChatRequest(WebSocket webSocket, String text, Session session) throws IOException {
        // 构造请求JSON
        String requestJson = Utils.buildChatRequestJson(appid, text);
        webSocket.send(requestJson);
    }

    private void processResponse(String text, Session session) {
        // 解析响应并发送到WebSocket客户端
        String partialAnswer = Utils.parseResponse(session, text);
        try {
            log.info("partialAnswer: {}", partialAnswer);
            session.getBasicRemote().sendText(partialAnswer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
